import React from 'react'
import PropTypes from 'prop-types'

export default function EventWrapper(props, context) {
  const {
    as: Tag,
    children,
    ...restProps
  } = props
  const { handlers } = context
  for (let key in restProps) {
    if (/on[A-Z][a-z]+/.test(key)) {
      const handler = handlers[restProps[key]]
      if ('function' === typeof handler) {
        restProps[key] = handler
      }
    }
  }
  return (
    <Tag {...restProps}>{children}</Tag>
  )
}

EventWrapper.contextTypes = {
  handlers: PropTypes.object,
}

EventWrapper.defaultProps = {
  as: 'a'
}